// pages/check/detail/todoDetail.js
const util = require('../../../utils/util.js')
let app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    obj:null,
    inspectionImplementId:'',
    showIndex1: 1,//巡检计划面板展开
    showIndex2: 2,//巡检执行面板展开
    resultList: ["正常", "异常"],//
    pictures: [],
    resultSelIndex:0,
    cameraHidden:true,
    imgHidden:true,
    tempSrc:'',//图片的临时路径
    id:null,
    undoCheckCount:0,
    permissions:[],
    loadingHidden:false
  },
  //预览图片
  imgYu(event) {
    //util.imgYu(event);
    util.imgYu2(event);
  },
  //删除图片
  delImg(e){
    var src = e.currentTarget.dataset.src;
    var id = e.currentTarget.dataset.id;
    var pics = this.data.pictures;
    console.log(e)
    for (var i = 0; i < pics.length; i++){
      if (pics[i] == src){
        pics.splice(i,1);
      }
    }
    this.setData({
      pictures:pics
    })
    wx.request({
      url: getApp().data.app_server + "/common/upload/delete",
      method: 'post',
      data: { id: id },
      success: function (res) {
        console.log(res);
      }
    })
  },
  // 巡检详情接口：/api/polling/get-polling-record-info 
  //获取详情信息
  doGetData(id) {
    let _this = this;
    _this.setData({
      loadingHidden: false
    })
    wx.request({
      url: getApp().data.app_server + "/weixin/polling/get-polling-record-info",
      method: 'post',
      data: { id: id },
      success: function (res) {
        console.log(res);
        let data = res.data.msg;
        var name = '';
        data.inspectionPlanEntity.inspectionStartDate = util.formatTimeStamp(data.inspectionPlanEntity.inspectionStartDate, 'Y-M-D h:m');
        if (data.inspectionImplementUsers != null) {
          for (var j = 0; j < data.inspectionImplementUsers.length; j++) {
            name = data.inspectionImplementUsers[j].userName + ',' + name;
          }
          name = name.substr(0, name.length - 1);
          data.inspectionImplementUsers = name;
        }
        let time = data.inspectionCycle - 100;
        let flag = 2;//0超时巡检，1已逾期，2正常巡检
        let flagInspection = 1;//0 待巡检，1已巡检
        if (time < new Date().getTime()) {
          if (data.inspectionExecute) {
            flag = 0;
          } else {
            flag = 1;
          }
        }
        if (!data.inspectionExecute) {
          flagInspection = 0;
        }
        data.flagInspection = flagInspection;
        data.flag = flag;
        _this.setData({
          loadingHidden: true,
          obj: data
        })

      }
    })
  },
  //巡检执行
  formSubmit(e){
    let _this = this;
    console.log(e.detail.value + "," + _this.data.inspectionImplementId + "," + _this.data.resultSelIndex);
    _this.setData({
      loadingHidden: true
    })
    wx.request({
      url: getApp().data.app_server + "/weixin/polling/add-execute",
      method: 'post',
      data: { 
        inspectionImplementId:_this.data.inspectionImplementId,
        inspectionRemarks: e.detail.value.content,
        inspectionResult: _this.data.resultSelIndex,
        id: _this.data.id,
        token:app.data.token
       },
      success: function (res) {
        console.log(res.data.code);
        let msg = '操作失败';
        if (res.data.code == 200){
          msg = '操作成功';
        } 
        _this.getUndoCheckCount(_this,app.data.token);
        wx.showModal({//无论成功失败都会提示响应信息
          title: '提示',
          showCancel: false,
          content: msg,
          success: (r) => {
            if (res.data.code == 200) {
              wx.navigateTo({
                url: '../index'
              })
            }
          }
        });
      }
    })
  },
  //待巡检条数
  getUndoCheckCount(_this, token) {
    var strDate = util.strDateTime(new Date().getTime());
    var endDate = util.endDateTime(new Date().getTime());
    wx.request({
      url: app.data.app_server + "/weixin/polling/get-polling-record-count",
      method: 'post',
      data: {
        token: token,
        isExecute: 0,//0为巡检 1已巡检
        startDate: strDate,
        endDate: endDate
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log(res);
        app.data.undoCheckCount = res.data.msg;
        console.log("undoCheckCount:" + _this.data.undoCheckCount)
        _this.setData({
          undoCheckCount: app.data.undoCheckCount
        })
      }
    })
  },
  //巡检结果选择
  bindPickerChange(e){
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      resultSelIndex: e.detail.value
    })
  },
  //工单信息面板折叠展开操作
  panel: function (e) {
    var i = 0
    if (e.currentTarget.dataset.index == 1) {
      if (e.currentTarget.dataset.index != this.data.showIndex1)
        i = e.currentTarget.dataset.index;
      this.setData({
        showIndex1: i
      })
    } else if (e.currentTarget.dataset.index == 2) {
      if (e.currentTarget.dataset.index != this.data.showIndex2)
        i = e.currentTarget.dataset.index;
      this.setData({
        showIndex2: i
      })
    } 
  },
  //选择拍照/相册上传
  selPhotoTyle(){
    var _this = this;
    console.log(_this);
    wx.showActionSheet({
      itemList: ['拍摄', '从相册选择'],
      success: function (res) {
        console.log(res);
        if (res.tapIndex == 0){//拍摄
          _this.setData({
            cameraHidden: false
          })
        }else{
          _this.chooseImgs();
        }
        if (!res.cancel) {
          console.log(res.tapIndex)
        }
      }
    });
  },
  //选择照片
  chooseImgs(){
    var _this = this;
    wx.chooseImage({
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        console.log(res.tempFilePaths);
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        /*_this.setData({
          pictures: _this.data.pictures.concat(res.tempFilePaths)
        });*/
        if (res.tempFilePaths){
          for (var i = 0; i < res.tempFilePaths.length; i++) {
            _this.fileUpload(res.tempFilePaths[i]);
          }
        }        
      }
    })
  },
  chooseImgFromCamera(){
    var _this = this;
    _this.setData({
      cameraHidden: true
    })
    wx.chooseImage({
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        console.log(res.tempFilePaths);
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
       /* _this.setData({
          pictures: _this.data.pictures.concat(res.tempFilePaths)
        });*/
        if (res.tempFilePaths) {
          for (var i = 0; i < res.tempFilePaths.length; i++) {
            _this.fileUpload(res.tempFilePaths[i]);
          }
        }
      }
    })
  },
  returnBack(e){
    var _this = this;
    _this.setData({
      cameraHidden: true
    })
  },
  //拍照
  takePhotoWithCamera(){
    var that = this;
    that.ctx.takePhoto({
      quality: 'high',
      success: (res) => {
        that.setData({
          tempSrc: res.tempImagePath,
          imgHidden: false,
          cameraHidden: true
        })
        console.log(res.tempImagePath);
      }
    })
  },
  //重新拍摄
  reTakePhoto(){
    this.setData({
      src: null,
      imgHidden: true,
      cameraHidden: false
    })
  },
  startUpload(){
    var _this = this;
    _this.setData({
     // pictures: _this.data.pictures.concat(_this.data.tempSrc),
      imgHidden: true,
      cameraHidden: true,
      tempSrc: _this.data.tempSrc
    })
    console.log(_this.data.pictures);
    _this.fileUpload(_this.data.tempSrc);
  },
  //上传附件
  fileUpload(tempFilePath){
    var _this = this;
    var upload_task = wx.uploadFile({
      url: getApp().data.app_server + "/common/upload/add/" + this.data.id, //仅为示例，非真实的接口地址
      filePath: tempFilePath,
      name: 'file',
      formData: {
      },
      success(res) {
        if (res.statusCode == 200){
          let data = JSON.parse(res.data);
          let realPath = app.data.app_server+'/weixin'+data.sqlPath+data.fileName;
          _this.setData({
            pictures: _this.data.pictures.concat({ 'id': data.id, 'realPath': realPath})
          })
        }
      },
      error(res){
        wx.showToast({
          title: '上传失败',
          icon: 'success',
          duration: 2000
        })
        console.log('上传失败');
      }
    })

    /*upload_task.onProgressUpdate((res) => {
      console.log('获取上传进度');
      console.log(res) 
      that.setData({
        upload_picture_list: upload_picture_list
      });
    });*/
  },
 
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.ctx = wx.createCameraContext();
    this.doGetData(options.id);
    let id = util.uuid();//附件要用，所以要先生成id
    console.log("生成id:" + id);
    this.setData({
      inspectionImplementId:options.id,
      id:id,
      undoCheckCount:app.data.undoCheckCount,
      permissions: app.data.permissions
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})